import router from '@/router'
import store from '@/store'

import NProgress from 'nprogress' // 引入一份进度条插件
import 'nprogress/nprogress.css' // 引入进度条样式

const whiteFile = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (!store.getters.id) {
        // 等待获取到数据之后再放行，使用await
        const { roles: { menus }} = await store.dispatch('user/getUserInfo')
        const asyncRoutes = await store.dispatch('permission/filterRotes', menus)
        router.addRoutes([...asyncRoutes, { path: '*', redirect: '/404', hidden: true }])
        next(to.path)
      } else {
        next()
      }
    }
  } else {
    if (whiteFile.some(obj => obj === to.path)) {
      next()
    } else {
      next('/login')
    }
  }
  NProgress.done() // 手动强制关闭一次  为了解决 手动切换地址时  进度条的不关闭的问题
})

router.afterEach(route => {
  NProgress.done()
})
